package com.ruoyi.framework.security.util;

import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.RySpringUtils;
import com.ruoyi.framework.aspectj.DataScopeAspect;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.project.system.domain.SysRole;
import com.ruoyi.project.system.domain.SysUser;

import java.util.List;

public class UserUtils {

    public static SysUser getCurrentUser() {
        LoginUser loginUser = RySpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        SysUser currentUser = loginUser.getUser();
        return currentUser;
    }

    public static int currentUserMaxDataScope() {
        SysUser currentUser = getCurrentUser();
        List<SysRole> roles = currentUser.getRoles();
        int maxScope = Integer.parseInt(DataScopeAspect.DATA_SCOPE_SELF);
        for (SysRole sysRole : roles) {
            int roleScope = Integer.parseInt(sysRole.getDataScope());
            if (roleScope < maxScope) {
                maxScope = roleScope;
            }
        }
        return maxScope;
    }

    /**
     * 检查用户修改数据权限
     *
     * @param dataScope 要修改的数据权限
     * @return true检查通过， false检查不通过
     */
    public static boolean checkUserDataScope(String dataScope) {
        if (StringUtils.isNotBlank(dataScope)) {
            int maxScope = currentUserMaxDataScope();
            if (maxScope > Integer.parseInt(dataScope)) {
                // 当前要修改得权限比自身权限高
                return false;
            }
        }
        return true;
    }

    /**
     * 取得该部门的租户ID
     * 
     * @param tenantId 租户ID
     * @param ancestors 父级列表
     * @return 该部门租户ID
     */
    public static Long turnIntoTenantId(Long tenantId, String ancestors) {
        List<String> deptIds = StringUtils.str2List(ancestors, ",", true, true);
        // 有父级节点
        if (deptIds.size() > 1) {
            return Long.parseLong(deptIds.get(1));
        }
        return tenantId;
    }
}
